<?php
/**
 * Build and send an HTTP response
 * 
 * @author Alan Moreau - moreau.alan@gmail.com
 *
 */
class Mac_Controller_HTTPResponse
{
    /**
     * HTTP status code handled
     * 
     * @var int
     */
    const HTTP_SUCCESS = 200;
    const HTTP_REDIRECTION_FOUND = 302;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    
    /**
     * HTTP [key]: [value] header
     * 
     * @var array[string] = string
     */
    private $headers = array();
    
    /**
     * HTTP inline headers
     * example : HTTP/1.1 301 
     * 
     * @var array[] = string
     */
    private $headersRaw = array();
    
    /**
     * HTTP response status code
     * 
     * @var int
     */
    private $httpResponseCode = null;
    
    /**
     * HTTP body response
     * 
     * @var string
     */
    private $body = '';
    
    /**
     * Indicate if cache headers must be sent
     * //TODO handle cache header
     * @var boolean
     */
    private $cache = false;
    
	/**
	 * Construct an HTTPResponse with default headers
	 * 
	 */
    public function __construct ()
    {
	    //set default headers
	    $this->headers['Content-Type'] = 'text/html; charset=utf-8';
	}
	
	/**
	 * Add HTTP [key]: [value] header 
	 * 
	 * @param string $headerKey
	 * @param string $headerValue
	 */
	public function addHeader ($headerKey, $headerValue)
	{
	    $this->headers[$headerKey] = $headerValue;
	}
	
	/**
     * Set all HTTP [key]: [value] headers 
     * 
     * @param array[string] = string $headers
     */
    public function setHeaders (array $headers)
    {
        $this->headers = $headers;
    }
    
    /**
     * Add HTTP inline header 
     * 
     * @param string $headerRaw
     */
    public function addHeaderRaw ($headerRaw)
    {
        $this->headersRaw[] = $headerRaw;
    }
    
    /**
     * Set all HTTP inline headers 
     * 
     * @param array[] = string $headersRaw
     */
    public function setHeadersRaw (array $headersRaw)
    {
        $this->headersRaw = $headersRaw;
    }
    
    /**
     * Defines the HTTP response status code 
     * 
     * @param int $code
     */
    public function setHttpResponseCode ($code)
    {
        $this->httpResponseCode = $code;
    }
    
    /**
     * Defines the HTTP body response
     * 
     * @param string $body
     */
    public function setBody ($body)
    {
        $this->body = $body;
    }
	
    /**
     * Send both headers and body to browser
     */
	public function send ()
	{
	    $this->sendHeaders();
	    echo $this->body;
	}
	
	/**
	 * Send defined headers
	 * 
	 */
	private function sendHeaders ()
	{
	    if($this->httpResponseCode != null){
	        header('HTTP/1.1 ' . $this->httpResponseCode);
	    }
	     
	    foreach($this->headersRaw as $headerRaw){
	        header($headerRaw);
	    }

	    foreach($this->headers as $headerKey => $headerValue){
	        header($headerKey . ': ' . $headerValue);
	    }
	}
}
